package com.ming.yourdiary.dataMannager;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import androidx.annotation.Nullable;

import com.ming.yourdiary.common.AppConstants;

public class DiaryDBOpenHelper extends SQLiteOpenHelper {
  //public static final String FILE_DIR = Environment.getExternalStorageDirectory().getPath() + "/SQLiteTest/";
  public static final int DATABASE_VERSION = AppConstants.DATABASE_VERSION;
  public static final String TABLE_NAME = AppConstants.TABLE_NAME;

  public DiaryDBOpenHelper(Context context, String tableName) {
    super(context, tableName, null, DATABASE_VERSION);
  }

  public DiaryDBOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
    super(context, name, factory, version);
  }

  public DiaryDBOpenHelper(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version, @Nullable DatabaseErrorHandler errorHandler) {
    super(context, name, factory, version, errorHandler);
  }

  /*初次生成数据库时调用 生成数据库表结构*/
  @Override
  public void onCreate(SQLiteDatabase db) {
    createDiaryNotesTable(db);
  }

  /*数据版本更新触发 例如字段更新 表的增加和删除*/
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (newVersion > oldVersion) {
      String sql = "DROP TABLE IF EXISTS " + TABLE_NAME;
      db.execSQL(sql);
      onCreate(db);
    }
  }

  /*
   * 表名：AppConstants.TABLE_NAME = diary_notes
   * id integer primary key autoincrement
   * title text
   * content text
   * weatherCode integer
   * createDate text
   * year int
   * month int
   * */
  public void createDiaryNotesTable(SQLiteDatabase db) {
    try {
      String sql = "create table if not exists " + TABLE_NAME +
        "(id integer primary key autoincrement,title text,content text,weatherCode integer,createDate text,year int,month int)";
      db.execSQL(sql);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}
